﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Storage.EntityModels;
using System.Collections.Generic;
using GeoRef;
using TripLOA.WebService.Wrappers;
using Groupware;


namespace GUI
{
    public partial class travelSearch : TripLOA.GUI.internationalization.LOABasePage
    {

        IEnumerable<Groupware.Trip> trips;


        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Trips"]== "All") 
            {
                content.Visible = true;
                DataBinding();    
            }
            if (Request.QueryString["Page"] != null)
            {
                content.Visible = true;
                DataBinding();
            }
        }


        /// <summary>
        /// Retrieves all trips that satisfy the search parameter(departure and arrival locations, tollerance in kilometer and departure's data)
        /// and initialize the global IEnumerable<Groupware.Trip> trips.
        /// If no trip is founded the list is empty.
        /// </summary>

        protected void DataBinding() 
        {
            int curPage = int.Parse(Request.QueryString["Page"] == null ? "0" : Request.QueryString["Page"]);

            bool geocode_exception = false;
            lblErrorLocalizationArr.Visible = false;
            lblErrorLocalizationDep.Visible = false;

            GeoQuery q = new GeoQuery();
            GeoLoc fromLoc = null;
            GeoLoc toLoc = null;
            Search.TripFieldParameter datePar = null;
            List<Search.TripFieldParameter> parList = new List<Search.TripFieldParameter>();
            int tollerance=2000;


            try { fromLoc = (latlongStart.Value != "") ? new GeoLoc(latlongStart.Value, txtStart.Text, "") : (txtStart.Text != "" ? q.geoCoding(txtStart.Text).First() : null); }
            catch (GeoRef.Exceptions.GeoCodingException) { geocode_exception = true;  lblErrorLocalizationDep.Visible = true; }

            try { toLoc = (latlongFinish.Value != "") ? new GeoLoc(latlongFinish.Value, txtFinish.Text, "") : (txtFinish.Text != "" ? q.geoCoding(txtFinish.Text).First() : null); }
            catch (GeoRef.Exceptions.GeoCodingException) { geocode_exception = true;  lblErrorLocalizationArr.Visible = true; }


            if (!geocode_exception)
            {
                

                switch (ddlTollerance.SelectedIndex)
                {
                    case 0: tollerance = 2000;
                        break;
                    case 1: tollerance = 1000;
                        break;
                    case 2: tollerance = 5000;
                        break;
                    case 3: tollerance = 10000;
                        break;
                    case 4: tollerance = 20000;
                        break;
                    case 5: tollerance = 50000;
                        break;
                    case 6: tollerance = 100000;
                        break;
                    default: tollerance = 2000;
                        break;
                }


                Search.TripParameter departureParameter = Search.TripParameter.Empty; //new TripParameter(fromLoc, tollerance, true);
                if (fromLoc != null)
                {
                    departureParameter.Point = fromLoc;
                    departureParameter.Radius = tollerance;
                    departureParameter.ExactMatch = false;
                }

                Search.TripParameter arrivalParameter = Search.TripParameter.Empty; //new TripParameter(toLoc, tollerance, true);
                if (toLoc != null)
                {
                    arrivalParameter.Point = toLoc;
                    arrivalParameter.Radius = tollerance;
                    arrivalParameter.ExactMatch = false;
                }


                DateTime dataViaggio;
                if (txtDate.Text != "")
                {
                    dataViaggio = DateTime.Parse(txtDate.Text);
                    datePar = Search.TripFieldParameter.Create<DateTime?>("DepartureDate",
                        d => d.HasValue && d.Value.Date >= dataViaggio.Date);
                }

                if (datePar != null)
                {
                    parList = new List<Search.TripFieldParameter>();
                    parList.Add(datePar);
                }

                //List < TripInfo > tripList = new List<TripInfo>();

                parList.Add(Search.TripFieldParameter.Create<bool>("Draft", d => d == false));

                //trips = Search.SearchManager.TripSearch(departureParameter, arrivalParameter, parList, null);
                trips = Groupware.TripManager.TripSearch(departureParameter, arrivalParameter, parList, null);
                gv_result.DataSource = trips;

                //mah two is mel che one
                gv_result.DataBind();
                if (curPage > 0 && curPage <= gv_result.PageCount)
                {
                    gv_result.PageIndex = curPage - 1;
                }
                gv_result.DataBind();
                
                int i = curPage - 5 > 0 ? curPage - 5 : 0;
                int to = i + 7 < gv_result.PageCount ? i + 7 : gv_result.PageCount;
                string html = "<div style=\"position:absolute; left:-9999px;\"><tr align=\"center\"><td colspan=\"6\">";
                html += "<table border=\"0\"><tbody><tr>";
                for (i = curPage - 5 > 0 ? curPage - 5 : 0; i < to; i++)
                {
                    if (i + 1 == curPage)
                    {
                        html += "<td><span>" + (int)(i + 1) + "</span></td>";
                    }
                    else
                    {
                        int i1 = i + 1;
                        html += "<td><a href=\"" + Request.RawUrl.Substring(0, Request.RawUrl.IndexOf('?') + 1) + "&Page=" + i1 + "\">" + i1 + "</a></td>";
                    }
                }
                html += " </tr></tbody></table></td>";
				html += "</tr></div>";
                
                gv_result.Controls.Add(new LiteralControl(html));
            }//end if

        }


        /// <summary>
        /// This method manage the search button click event.
        /// </summary>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            content.Visible = true;
            DataBinding();            
            
        }

        /// <summary>
        /// Check if trip is expired.
        /// </summary>
        /// <param name="expirationDate">trip expiration date</param>
        /// <param name="departureDate">trip departure date</param>
        /// <returns>true if trip is expired, false otherwise</returns>
        protected bool tripExpired(String expirationDate, String departureDate)
        {
            if (expirationDate != "" && departureDate != "")
                return (DateTime.Now.Date.CompareTo(DateTime.Parse(expirationDate).Date) > 0 || DateTime.Now.Date.CompareTo(DateTime.Parse(departureDate).Date) > 0);
            return false;
        }


        /// <summary>
        /// This method manage the page changing on the bottom of result's panel.
        /// </summary>
        protected void PageChanged(object sender, GridViewPageEventArgs e)
        {
            gv_result.PageIndex = e.NewPageIndex;
            DataBinding();
        }

        protected void gv_result_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


     
    }
    
}
